<template>
  <div>
    <canvas type="2d" id="myCanvas" :hidden="false"></canvas>
    <button class="btn" @click="toSaveImage">保存</button>
  </div>
</template>
<script>
var canvas;
export default {
  data() {
    return {
      sharePath: "",
      qrCode:
        "https://img.lvyouquan.cn/uploads/media/images/multiple/20200519/6668321872750325760_972_1296.jpg",
      posterUrl:
        "https://img.lvyouquan.cn/uploads/media/images/multiple/20200519/6668321872750325760_972_1296.jpg"
    };
  },
  created() {},
  onReady() {
    this.getCavas();
  },
  methods: {
    getCavas() {
      const query = wx.createSelectorQuery();
      query
        .select("#myCanvas")
        .fields({ node: true, size: true })
        .exec(res => {
          canvas = res[0].node;
          const ctx = canvas.getContext("2d");
          const { pixelRatio, screenWidth } = wx.getSystemInfoSync();
          const dpr = 2;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
          //绘制背景色
          ctx.fillStyle = "#fff";
          ctx.fillRect(0, 0, screenWidth, canvas.height);

          //绘制内容

          this.toDrawCanvas(ctx, screenWidth);
        });
    },
    async toDrawCanvas(ctx, imgW) {
      const posterH = 630;
      const posterImg = await this.loadImage(this.posterUrl);

      ctx.drawImage(posterImg, 0, 0, imgW, posterH);

      //绘制透明背景
      ctx.save();
      ctx.globalAlpha = 0.7;
      ctx.fillStyle = "#000";
      ctx.fillRect(0, 0, imgW, 34);
      ctx.fillRect(0, posterH - 70, imgW, 70);
      ctx.restore();

      this.toDrawQrCode(ctx, 0, posterH);
      this.toDrawAvaer(ctx, imgW);
      this.toDrawText(ctx, posterH, imgW);
    },
    async toDrawQrCode(ctx, x, y) {
      const qrCodeImg = await this.loadImage(this.qrCode);
      ctx.drawImage(qrCodeImg, x + 25, y - 100, 90, 90);
    },
    async toDrawAvaer(ctx, imgW) {
      const avatarH = 24;
      const avaerImg = await this.loadImage(this.qrCode);
      ctx.save();
      ctx.beginPath(); //开始绘制
      ctx.arc(
        avatarH / 2 + 65,
        avatarH / 2 + 5,
        avatarH / 2,
        0,
        Math.PI * 2,
        false
      );
      ctx.clip();
      ctx.drawImage(avaerImg, 65, 5, avatarH, avatarH);
      ctx.restore();
    },
    toDrawText(ctx, y, screenWidth) {
      const padding = 20;
      ctx.textAlign = "center";
      ctx.font = "14px PingFang SC";
      ctx.fillStyle = "#ffffff";

      ctx.fillText(
        "每一刻都是美丽时光",
        screenWidth / 2 + 14,
        23,
        screenWidth
      );

      ctx.textAlign = "left";
      ctx.fillText("全景湘西热卖红心火龙果基地采摘…", padding + 110, y - 45);

      ctx.font = "13px PingFang SC";
      ctx.fillText("【长按图片识别二维码】", padding + 104, y - 20);
    },
    loadImage(url) {
      return new Promise((resolve, reject) => {
        let img = canvas.createImage();
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = url;
      });
    },
    toSaveImage() {
      // if (!this.finished) {
      //     uni.showToast({
      //         title: '正在生成图片，稍后再试',
      //         icon: 'none'
      //     })
      //     return
      // }
      uni.canvasToTempFilePath(
        {
          canvas: canvas,
          fileType: "jpg",
          // width: this.canvasW * 2,
          // height: this.canvasH * 2,
          // destWidth: this.canvasW * 2,
          // destHeight: this.canvasH * 2,
          quality: 1,
          success: res => {
            this.sharePath = res.tempFilePath;
            this.saveImageToPhotosAlbum(res.tempFilePath);
            console.log(res.tempFilePath);
          },
          fail(err) {
            console.log(err);
            uni.showToast({
              icon: "none",
              title: "保存失败"
            });
          }
        },
        this
      );
    },
    saveImageToPhotosAlbum(path) {
      uni.saveImageToPhotosAlbum({
        filePath: path,
        success: () => {
          uni.showToast({
            title: "图片已经保存到相册\n快去分享吧",
            duration: 3000,
            icon: "none"
          });
          this.show = false;
        },
        fail: () => {
          wx.getSetting({
            success: res => {
              if (!res.authSetting["scope.writePhotosAlbum"]) {
                uni.showModal({
                  title: "保存失败",
                  content: "请同意访问您的相册",
                  success: res => {
                    if (res.confirm) {
                      wx.openSetting();
                    } else if (res.cancel) {
                      this.show = false;
                    }
                  }
                });
              }
            }
          });
        }
      });
    },
    getImageInfo(url) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: url,
          success: res => {
            return resolve(res);
          },
          fail: err => {
            console.error(url);
            return reject(err);
          }
        });
      });
    }
  }
};
</script>
<style>
canvas {
  width: 100%;
  height: 1260rpx;
}
</style>